/**
 * CEP Mobile Manager on Android July 2012 
 */
package com.orange.cepmanager.android.gcm;
import static com.orange.cepmanager.android.CEPManagerCommon.*;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.google.android.gcm.GCMRegistrar;
import com.orange.cepmanager.android.rest.CEPManagerREST;

/**
 * Helper class used to communicate with the server app engine and server GCM.
 * @author FAIROUZ OUBENALI
 *
 */
public class GCMServer {
	private static String regId="";

	/**
	 * @param context
	 * @return
	 */
	private static boolean manifestPermission(Context context) {
		// Make sure the device has the proper dependencies.
		GCMRegistrar.checkDevice(context);
		// Make sure the manifest was properly set - comment out this line
		// while developing the app, then uncomment it when it's ready.
		GCMRegistrar.checkManifest(context);
		return true;
	}

	/**
	 * @param context
	 * @return
	 */
	public static boolean register(Context context) {
		Log.i(GCM_SERVER_TAG, "register **" + context);
		if (manifestPermission(context) == false)
			return false;
		else if (checkNotNull(SERVER_URL, SENDER_ID) == false)
			return false;
		else {
			GCMRegistrar.checkDevice(context);
			GCMRegistrar.checkManifest(context);
			getRegistrationId(context);
			if (regId.equals("")) {
				// Automatically registers application on startup.
				Log.i(GCM_SERVER_TAG,
						"register, phone not registered yet ::SENDER_ID **"
								+ SENDER_ID);
				GCMRegistrar.register(context, SENDER_ID);
				Log.i(GCM_SERVER_TAG,
						"register, regId **"
								+ GCMRegistrar.getRegistrationId(context));

			} else {
				// Device is already registered on GCM, check server.
				if (GCMRegistrar.isRegisteredOnServer(context)) {
					// Skips registration.
					Log.i(GCM_SERVER_TAG,
							"phone already exist on GCM  ... pas pour l'instant:: regId **"
									+ getRegistrationId(context));
				} else {
					// thread register on server app engine
					// AsyncTaskServerAppEngine(context);
				}
			}
			return true;
		}
	}

	/**
	 * @param context
	 * @param regId
	 */
	public static void unregister(final Context context, final String regId) {
		Log.i(GCM_SERVER_TAG, "unregistering device (regId = " + regId + ")");
		try {
			GCMRegistrar.setRegisteredOnServer(context, false);
			CEPManagerREST.unregisterOnAppEngine(context, regId);
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(GCM_SERVER_TAG, "IO error " + e);
		}

	}

	/**
	 * @param context
	 * @return
	 */
	public static final String getRegistrationId(Context context) {
		regId = GCMRegistrar.getRegistrationId(context);
		Log.i(GCM_SERVER_TAG, "getRegistrationId *** " + regId);
		return regId;
	}

	/**
	 * @param refUrl
	 * @param refSenderID
	 * @return
	 */
	private static boolean checkNotNull(String refUrl, String refSenderID) {
		if (refUrl == null) {
			// throw new NullPointerException(
			// getString(R.string.error_config, name));
			Log.e(GCM_SERVER_TAG, "IO error SERVER_URL:: " + SERVER_URL);
			return false;
		} else if (refSenderID == null) {
			Log.e(GCM_SERVER_TAG, "IO error SENDER_ID:: " + SENDER_ID);
			return false;
		} else
			return true;
	}

	/**
	 * @param context
	 */
	public static void AsyncTaskServerAppEngine(final Context context) {
		// Try to register again, but not in the UI thread.
		// It's also necessary to cancel the thread onDestroy(),
		// hence the use of AsyncTask instead of a raw thread.
		mRegisterTask = new AsyncTask<Void, Void, Void>() {

			@Override
			protected Void doInBackground(Void... params) {
				// Log.i(GCM_SERVER_TAG,
				// " try to connect on the server app engine");
				boolean registered = CEPManagerREST.registerOnAppEngine(
						context, regId);

				// At this point all attempts to register with
				// the app server failed, so we need to unregister the
				// device from GCM - the app will try to register again
				// when it is restarted. Note that GCM will send an
				// unregistered callback upon completion, but
				// GCMIntentService.onUnregistered() will ignore
				// it.
				if (!registered) {
					GCMRegistrar.unregister(context);
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				mRegisterTask = null;
			}

		};
		mRegisterTask.execute(null, null, null);

	}

}
